package com.lu.integrate.gateway.utils;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import com.alibaba.fastjson.JSON;
import com.lu.stack.common.model.response.R;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Description 使用给定的Publisher者将消息正文写入底层HTTP层.
 * @Author jianglong
 * @Date 2020/05/19
 * @Version V1.0
 */
public class HttpResponseUtils {

    /**
     * 自定义输出
     * @param response
     * @param statusCode
     * @param r
     */
    public static Mono<Void> write(ServerHttpResponse response, HttpStatus statusCode, R r){
        response.setStatusCode(statusCode);
        response.getHeaders().add(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue());
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONString(r).getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }

}
